<template>
  <div class="app-container book-content">
    <fullscreen  ref="fullscreen" @change="fullscreenChange">
      <div class="content" id="content">
        <span class="fade" v-show="isMenu||isSetting" @click="closePop"></span>
        <div id="area" v-loading="loading" :style="'background:'+bgColor"></div>
        <div class="page">
          <span class="next" @click="next" ></span>
          <span class="prev" @click="prev" ></span>
        </div>
        <div :class="['menu-list',{active:isMenu}]">
          <div class="list-content">
            <span class="title">目录</span>
            <div class="list-area">
              <ul>
                <li v-for="(item,index) in toc" :key="index" @click="gotoDirectory(item)" >
                  <span>{{item.label}}</span>
                </li>
              </ul>
            </div>
          </div>
          <img class="close" @click="isMenu= false" src="/static/images/book/close.png" alt="">
        </div>
        <div :class="['set-list',{active:isSetting}]">
          <div class="set-list-content">
            <span class="title">设置</span>
            <div class="theme">
              <span>阅读主题</span>
              <span :class="['theme-item',{'active':bgIndex===index}]" v-for="(item,index) in theme" :key="index" @click="setFontSize(1,index,item)"
              ></span>
            </div>
            <div class="fontFamily">
              <span>正文字体</span>
              <span v-for="(item,index) in familyList" :class="['family-item',{'active':familyIndex===index}]" :key="index" @click="setFontSize(2,index,item)">{{item.name}}</span>
            </div>
            <div class="fontSize">
              <span>字体大小</span>
              <span :class="['size-item',{'active':fontIndex===index}]" v-for="(item,index) in sizeList" :key="index" @click="setFontSize(3,index,item)">{{item.name}}</span>
            </div>
            <div class="btn">
              <el-button type="primary" @click="saveOptions" round >保存</el-button><br>
              <el-button type="primary" @click="cancelOptions" round >取消</el-button>
            </div>
            <img class="close" @click="isSetting= false" src="/static/images/book/close.png" alt="">
          </div>
        </div>
        <div class="menu">
           <!-- <span class="bookmark" @click="">
          <i class="iconfont icon1"></i>
          书签</span>  -->
          <span class="fullscreen" @click="toggle">
            <i class="iconfont icon2"></i>全屏
          </span>
          <span class="bookmark" @click="openMenu" >
            <i class="iconfont icon3"></i> 目录</span>
        </div>
        <div class="pageList">
          <span>{{percentage}}%</span>
        </div>
        <div class="history" @click="$router.back()">
          <img src="/static/images/base/history.png" alt="" >
          <div>返回</div>
        </div>
         <!-- <div class="download">
              <img src="/static/images/base/download.png" alt="">
              <div>下载</div>
           </div> -->
        <div class="setting" @click="setting" >
          <img src="/static/images/base/setting.png" alt="" >
          <div>设置</div>
        </div>
      </div>
    </fullscreen>
  </div>
</template>

<script>
import { GetBookInfoList } from "@/api/Api";
import { readRecord } from "@/api/index";
import fullscreen from "vue-fullscreen";
import Epub from "epubjs";
import Vue from "vue";
import { setTimeout } from 'timers';
Vue.use(fullscreen);
global.ePub = Epub;
export default {
  data() {
    return {
      epubBook:{},
      displayed:'',
      book: "",
      isMenu: false,
      isSetting: false,
      active: -1,
      currentPage: 0,
      total: 0,
      toc: [],
      fullscreen: false,
      bgColor:'',
      options: {
        bgColor: "#CFD8BD",
        color: "#000",
        fontFamily: "SimSun, Songti SC, Songti TC",
        fontSize: "16px"
      },
      theme: [
        {
          value: "#ECECEC",
          color: "#000"
        },
        {
          value: "#DEDACF",
          color: "#000"
        },
        {
          value: "#D3C7B1",
          color: "#000"
        },
        {
          value: "#CFD8BD",
          color: "#000"
        },
        {
          value: "#b8dbbd",
          color: "#000"
        },
        {
          value: "#989898",
          color: "#fff"
        }
      ],
      familyList: [
        {
          name: "雅黑",
          value: "Microsoft Yahei, Heiti SC, Heiti TC"
        },
        {
          name: "宋体",
          value: "SimSun, Songti SC, Songti TC"
        },
        {
          name: "楷体",
          value: "KaiTi, Kaiti SC, Kaiti TC"
        }
      ],
      sizeList: [
        {
          name: "小",
          size: "16px"
        },
        {
          name: "中",
          size: "20px"
        },
        {
          name: "大",
          size: "24px"
        },
        {
          name: "特大",
          size: "28px"
        }
      ],
      locationCfi: "",
      fontIndex:0,
      bgIndex:0,
      familyIndex:0,
      screenWidth: document.body.clientWidth,   // 这里是给到了一个默认值 （这个很重要）,
      loading:true,
      percentage:0,
    };
  },
  components: {},
  created() {
      document.onkeydown = function(e) {            
        let key = window.event.keyCode;            
        if (key ==  27) {
        this.fullscreen == false
                console.log('ESC')
            }
        };
     this.init();
      
  },

  mounted() {
      
  },
  methods: {
    resized(){
      var _this = this
       return new Promise((relove,rejoect)=>{
          window.onresize = function windowResize () {
                // 通过捕获系统的onresize事件触发我们需要执行的事件
                this.areaH = document.getElementById("content").offsetHeight
                this.areaW = document.getElementById("content").offsetWidth  
                setTimeout(()=>{
                  relove({
                    areaH:this.areaH,
                    areaW:this.areaW
                  })
                })
             if (!_this.checkFull()) {
                    //要执行的动作
                     setTimeout(()=>{
                      _this.epubBook.rendition.resize('100%','100%')
                  })
                   
                }
            } 
      })
    },
    init() {
      if (this.$route.query.url) {
        this.loadBook(this.$route.query.url);
      } else {
        GetBookInfoList(this.$route.query.bookId).then(result => {
           let book = result.data;
           let bookurl = book.filesPathList[0].fileResourcePath
           this.loadBook(bookurl);
           readRecord( book.bookName, 1, book.bookId, book.bookIntroduction, book.cover, book.author ).then(res => {
            console.log(res.data);
          });
        });
      }
    },
    checkFull() {
        var isFull = document.fullscreenEnabled || window.fullScreen || document.webkitIsFullScreen || document.msFullscreenEnabled;
        //to fix : false || undefined == undefined
        if (isFull === undefined) {isFull = false;}
        return isFull;
    },
    toggle() {
        this.$refs['fullscreen'].toggle() 
        this.resized()
          .then(res=>{
              this.epubBook.rendition.resize('100%','100%')
          })
    },
    fullscreenChange (fullscreen) {
        this.fullscreen = fullscreen
      },
    //保存设置
    saveOptions() {
      this.setEpubStyle();
      this.closePop();
    },
    //取消设置
    cancelOptions() {
      this.closePop();
    },
    setFontSize(id,index, item) {
      if (id == 1) {
        this.bgIndex = index
        this.options.bgColor = item.value;
        this.options.color = item.color;

      } else if (id == 2) {
        this.familyIndex = index
        this.options.fontFamily = item.value;
      } else if (id == 3) {
        console.log(item.size)
         this.fontIndex = index
         this.options.fontSize = item.size;
        //  this.epubBook.rendition.themes.fontSize(item.size)
      }
    },
    //设置epub内容样式
    setEpubStyle() {
      let option = this.options;
      this.displayed.themes.override("font-size", option.fontSize);
      this.displayed.themes.override("background-color", option.bgColor);
      this.displayed.themes.override("font-family", option.fontFamily);
      this.displayed.themes.override("color", option.color);
      this.bgColor = option.bgColor;
      console.log(this.options)
      //   this.book.setStyle("background-color",this.themes[this.options.theme].bgColor);
    },
    //点击目录前往
    gotoDirectory(item) {
       this.closePop();
       this.displayed.display(item.href);   
       console.log(this.displayed)   
       this.percentage = parseInt(this.displayed.location.start.index/this.displayed.book.packaging.spine.length*100 )
       console.log(this.percentage)
    },
    // 关闭弹框
    closePop() {
      this.isMenu = false;
      this.isSetting = false;
    },
    // 打开设置
    setting() {
      this.isMenu = false;
      this.isSetting = !this.isSetting;
    },
    // 打开目录
    openMenu() {
      this.isSetting = false;
      this.isMenu = !this.isMenu;
    },
    // 加载书籍
    loadBook(path) {
      var book = new ePub(path);
       this.epubBook = book
       book.loaded.navigation.then(s=>{
         console.log(s.toc)
           this.toc = s.toc
           this.loading = false
       })
       book.loaded.metadata.then(s=>{
           this.metadata = s
       })
       var rendition = book.renderTo("area", {
            restore: true, // Skips parsing epub contents, loading from localstorage instead
            storage: false, // true (auto) or false (none) | override: 'ram', 'websqldatabase', 'indexeddb', 'filesystem'
            spreads: true, // Displays two columns
            fixedLayout : false, //-- Will turn off pagination
            styles : {}, // Styles to be applied to epub
            width : "100%", //width和height可以设置图书内容的宽和高，默认值是不设置，此时会填满父窗口。
            height: "100%", 
       }) 
       rendition.themes.fontSize('15px')
       this.displayed = rendition;
       this.displayed.display()
       console.log(this.displayed.display())
    },
    // 上一页
    prev() {
      this.displayed.prev();
      this.percentage = parseInt(this.displayed.location.start.index/this.displayed.book.packaging.spine.length*100 )
    },
    // 下一页
    next() {
     this.displayed.next();
      this.percentage = parseInt(this.displayed.location.start.index/this.displayed.book.packaging.spine.length*100 )
    },
  }
};
</script>
<style >
.area >>> img {
  width: 100% !important;
}
</style>

<style lang="less" scoped>
.custom-dz {
  .book-content .content .history {
    background: #e93926;
  }
  .book-content .content .download {
    background: #e93926;
  }
  .book-content .content .setting {
    background: #e93926;
  }
}
.book-content {
  .content {
    width: 966px;
    height: 642px;
    background: #f8f3e9;
    margin: 66px auto;
    border-radius: 10px;
    position: relative;
    box-shadow: #e6e6e6 2px 6px 2px;
    .fade {
      width: 100%;
      height: 100%;
      position: absolute;
      top: 0px;
      left: 0px;
      background: rgba(0, 0, 0, 0.7);
      cursor: pointer;
    }
    .menu-list {
      height: 100%;
      width: 0;
      background: #fff;
      position: absolute;
      right: 0px;
      top: 0px;
      transition: all 0.3s;
      overflow: hidden;
      .list-content {
        position: relative;
        width: 483px;
        height: 100%;
        .list-area {
          overflow-y: scroll;
          height: calc(100% - 100px);
          ul {
            padding: 0;
            li {
              cursor: pointer;
              padding: 15px;
              color: #80807c;
              display: flex;
              justify-content: space-between;
            }
            li:hover {
              background: rgba(0, 0, 0, 0.1);
            }
          }
        }
        .list-area::-webkit-scrollbar {
          display: none;
        }
      }
      .title {
        margin: 35px auto 20px auto;
        width: 294px;
        height: 45px;
        line-height: 45px;
        text-align: center;
        display: block;
        background-color: #f2ebe5;
        border-radius: 5px;
        color: #80807c;
        font-size: 18px;
      }
      .close {
        position: absolute;
        top: 20px;
        right: 26px;
        cursor: pointer;
        user-select: none;
      }
    }
    .menu-list.active {
      width: 483px;
    }
    .set-list {
      height: 100%;
      width: 0;
      background: #fff;
      position: absolute;
      left: 0px;
      top: 0px;
      transition: all 0.1s;
      overflow: hidden;
      .set-list-content {
        width: 500px;
        .title {
          display: block;
          padding: 20px 20px 48px 20px;
          font-size: 24px;
        }
        .close {
          position: absolute;
          top: 20px;
          right: 26px;
          cursor: pointer;
          user-select: none;
        }
        // 主题
        .theme {
          padding-left: 20px;
          display: flex;
          align-items: center;
          .theme-item {
            display: inline-block;
            width: 44px;
            height: 44px;
            background: url("/static/images/book/color.png") no-repeat;
            margin-left: 22px;
            cursor: pointer;
          }
          .theme-item:nth-child(2) {
            margin-left: 14px;
          }
          .theme-item:nth-child(3) {
            background-position: -44px 0;
          }
          .theme-item:nth-child(4) {
            background-position: -88px 0;
          }
          .theme-item:nth-child(5) {
            background-position: -132px 0;
          }
          .theme-item:nth-child(6) {
            background-position: -176px 0;
          }
          .theme-item:nth-child(7) {
            background-position: -220px 0;
          }
          .theme-item.active {
            background-position-y: -44px;
          }
        }
        // 字体
        .fontFamily {
          display: flex;
          padding-left: 20px;
          margin-top: 18px;
          align-items: center;
          font-size: 16px;
          user-select: none;
          .family-item {
            padding: 10px 35px;
            border: 2px solid #c1c1c1;
            border-radius: 5px;
            cursor: pointer;
            margin-left: 22px;
          }
          .family-item.active {
            border-color: #d9240d;
          }
        }
        // 字体大小
        .fontSize {
          display: flex;
          padding-left: 20px;
          margin-top: 18px;
          align-items: center;
          font-size: 16px;
          user-select: none;
          .size-item {
            border: 1px solid #c1c1c1;
            border-radius: 50%;
            cursor: pointer;
            margin-left: 22px;
            width: 44px;
            height: 44px;
            text-align: center;
            line-height: 44px;
          }
          .size-item.active {
            background: #15c798;
            border-color: #15c798;
            color: #fff;
          }
        }
        .btn {
          display: flex;
          justify-content: space-between;
          padding: 0 100px;
          margin-top: 250px;
          .el-button {
            background-color: #fff;
            line-height: 32px;
            width: 110px;
            font-size: 16px;
            padding: 0px 20px;
            border: 2px solid transparent;
            border-color: #15c798;
            color: #000;
            .el-button--primary:focus,
            .el-button--primary:hover {
              background-color: #15c798;
            }
          }
          .el-button:first-child {
            background-color: #15c798;
            border-color: #15c798;
            color: #fff;
          }
        }
      }
    }
    .set-list.active {
      width: 500px;
    }
    #area {
      padding: 20px 50px;
      width: calc(100% - 100px);
      height: calc(100% - 33px);
      overflow: hidden;
      border-radius: 10px;
    }
    .page {
      width: 78px;
      height: 302px;
      background: #f8f3e9;
      position: absolute;
      border-radius: 10px;
      right: -98px;
      bottom: 20px;
      .prev,
      .next {
        display: block;
        height: 150px;
        position: relative;
        cursor: pointer;
      }
      .next {
        border-bottom: 1px solid #e8e3da;
      }
      .prev:after {
        content: "";
        position: absolute;
        left: calc(50% - 5px);
        top: calc(50% - 10px);
        display: inline-block;
        width: 20px;
        height: 20px;
        border-top: 2px solid #000;
        border-right: 2px solid #000;
        transform: rotate(-135deg);
      }
      .next:after {
        content: "";
        position: absolute;
        left: calc(50% - 15px);
        top: calc(50% - 10px);
        display: inline-block;
        width: 20px;
        height: 20px;
        border-top: 2px solid #000;
        border-right: 2px solid #000;
        transform: rotate(45deg);
      }
    }
    .pageList {
      height: 50px;
      position: absolute;
      right: -110px;
      top: 250px;
      width: 78px;
      span {
        display: block;
        line-height: 50px;
      }
    }
    .menu {
      width: 78px;
      background: #f8f3e9;
      position: absolute;
      border-radius: 10px;
      right: -98px;
      top: 58px;
      span {
        display: block;
        height: 67px;
        // line-height: 77px;
        text-align: center;
        border-bottom: 1px solid #e8e3da;
        cursor: pointer;
        padding-top: 10px;
        .iconfont {
          display: block;
          background: url("/static/images/book/menu.png") no-repeat;
          width: 30px;
          height: 30px;
          margin: 0 auto;
        }
        .iconfont.icon2 {
          background-position: -30px 0;
        }
        .iconfont.icon3 {
          background-position: -60px 0;
        }
      }

      span:last-child {
        border-bottom: none;
      }
    }
    .history,
    .download,
    .setting {
      width: 60px;
      height: 60px;
      text-align: center;
      border-radius: 10px 0 0 10px;
      position: absolute;
      background: #15c798;
      cursor: pointer;
      img {
        width: 30px;
        height: 30px;
        display: block;
        margin: 5px auto 0 auto;
      }
      div {
        // flex: 1;
        color: #fff;
        font-size: 14px;
        display: block;
        position: relative;
      }
    }
    .history {
      left: -60px;
      top: 20px;
    }
    .download {
      left: -60px;
      top: 100px;
    }
    .setting {
      left: -60px;
      top: 100px;

      // top: 180px;
    }
  }
  .fullscreen .content {
    width: 80%;
    height: 80%;
  }
 
}
</style>